/**
 * 
 */
package com.yuyi.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.yuyi.model.SysPermission;
import com.yuyi.model.SysRole;
import com.yuyi.model.UserInfo;
import com.yuyi.service.UserInfoService;

/**
 * @author mcb 
 *
 * 2018年8月20日 下午4:04:19 
 */
public class MyShiroRealm extends AuthorizingRealm {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	@Qualifier("userInfoService")
	private UserInfoService userInfoService;
	
//	private final String salt="8d78869f470951332959580424d4bf4f";
	
	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
	        throws AuthenticationException {
	    //获取用户的输入的账号.
	    String username = (String)token.getPrincipal();
	    logger.info("用户名： {}",username);
	    //通过usernames从数据库中查找 User对象，如果找到，没找到.
	    //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
	    UserInfo userInfo = userInfoService.findByUsername(username);
	    if(userInfo == null){
	        return null;
	    }
	    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
	    		userInfo, //用户对象--数据库
	            userInfo.getPassword(), //密码--数据库
	            ByteSource.Util.bytes(userInfo.getSalt()),
	            getName()  //realm name
	    );
	    
	    
	    
	    return authenticationInfo;
	}
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	    System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
	    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
	    UserInfo userInfo  = (UserInfo)principals.getPrimaryPrincipal();
	    
	    System.out.println(userInfoService.getListRole(userInfo.getId()));
	    	    
	    List <SysRole>list=userInfoService.getListRole(userInfo.getId());
	    
	    for(SysRole role:list){
	        authorizationInfo.addRole(role.getRole());
	        logger.info("角色名： {}",role.getRole());
	        for (SysPermission sysPerm : userInfoService.getListPermission(role.getId())) {
	        	authorizationInfo.addStringPermission(sysPerm.getPermission());
			}
	    }
	   return authorizationInfo;
	}
	
	
	
}
